/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-03-20 16:29:53
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-03-28 14:31:52
 * @FilePath: /etws-sxk2307/tools/spidev/spi.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "spi.h"
static uint32_t SPIMODE = SPI_MODE_0;	// 上升沿，极性
static uint8_t SPIBITS = 8;
static uint32_t MAXSPEED = 5000000;  //5000000
int spiInit(const char* dev_path)
{

    int ret = 0;
    
    int g_devSpide0Fd = open(dev_path, O_RDWR);
    if(-1 == g_devSpide0Fd){
        printf("open g_szSPIFile error.\r\n");
        return -1;
    }
    //设置写入SPI模式
    ret = ioctl(g_devSpide0Fd, SPI_IOC_WR_MODE,&SPIMODE);
    if(ret < 0){
        printf("set SPI_IOC_WR_MODE error.\r\n");
        return -1;
    }
    //设置读取SPI模式
    ret = ioctl(g_devSpide0Fd, SPI_IOC_RD_MODE, &SPIMODE);
    if(ret < 0){
        printf("set SPI_IOC_RD_MODE error.\r\n");
        return -1;
    } 
    //设置SPI写入设备的字长
    ret = ioctl(g_devSpide0Fd, SPI_IOC_WR_BITS_PER_WORD, &SPIBITS);
    if(ret < 0){
        printf("set SPI_IOC_WR_BITS_PER_WORD per word error.\r\n");
        return -1;
    }
    //设置SPI读出设备的字长
    ret = ioctl(g_devSpide0Fd, SPI_IOC_RD_BITS_PER_WORD, &SPIBITS);
    if(ret < 0){
        printf("set SPI_IOC_RD_BITS_PER_WORD per word error.\r\n");
        return -1;
    }
//设置写入SPI设备的最大通信速率
   ret = ioctl(g_devSpide0Fd,SPI_IOC_WR_MAX_SPEED_HZ,&MAXSPEED);
   if( ret == -1){
        printf("SPI_IOC_WR_MAX_SPEED_HZ error.\r\n");
   }
   //设置读取SPI设备的最大通信频率
   ret = ioctl(g_devSpide0Fd,SPI_IOC_RD_MAX_SPEED_HZ,&MAXSPEED);
   if( ret == -1){
        printf("SPI_IOC_RD_MAX_SPEED_HZ error.\r\n");
   }
    return g_devSpide0Fd;
}



int spiTransmit(int fd, uint8_t *wdata, size_t wbytes, uint8_t *rdata, size_t rbytes)
{
    if(-1 == fd){
        printf("Error: spi Fd is not inited.\r\n");
        return -1;
    }
    if(wdata == NULL && rdata == NULL){
        printf("Error: spi wdata is not nullptr.\r\n");
        return -1;
    }
    struct spi_ioc_transfer tr[2];
    int num = 0;
    memset(tr, 0, sizeof(tr));
    if (wdata != NULL) {
        tr[num].tx_buf = (unsigned long)wdata;
        tr[num].rx_buf = NULL;
        tr[num].len = wbytes;
        num++;
    }
    if (rdata != NULL) {
        tr[num].tx_buf = NULL;
        tr[num].rx_buf = (unsigned long)rdata;
        tr[num].len = rbytes;
        num++;
    }

    int ret = ioctl(fd, SPI_IOC_MESSAGE(num), &tr);
    if(ret < 0) {
        printf("Error: spi SPI_IOC_MESSAGE.\r\n");
    }

    return ret;
}